package com.tieto.springboot.demo.springbootweb;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tieto.springboot.demo.springbootweb.bean.User;

@Controller
public class LoginController {

	private static final String MODEL_NAME_MAIN_PAGE = "mainPage";
	private static final String MODEL_NAME_LOGIN_PAGE = "loginPage";
	
	@RequestMapping("/mainPage")
	public String checkLogin(Model model,HttpSession session){
		if(session.getAttribute("userName") != null){			
			return MODEL_NAME_MAIN_PAGE;
		}
		else{
			return MODEL_NAME_LOGIN_PAGE;
		}
	}
	
	@RequestMapping("/login")
	public void login(Model model,HttpSession session,HttpServletRequest reqeust,HttpServletResponse response){
		String userName = reqeust.getParameter("userName");
		session.setAttribute("userName", userName);
		
		User user = new User();
		user.setUserName(userName);
		user.setAge(20);
		user.setId(UUID.randomUUID().toString());
		user.setPassword("123456");
		user.setSex("男");
		session.setAttribute("user", user);
		
		try {
			response.sendRedirect("/rootpath/mainPage");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
